﻿using System;
using System.Data;
using System.Data.Odbc;

namespace NahidaPrjoect4CSharp.Database
{
    public class ODBC : IDisposable
	{
		private readonly OdbcConnection _connection;
		private OdbcTransaction _transaction;
		private bool _isTransactionActive;

		public ODBC(string connectionString)
		{
			_connection = new OdbcConnection(connectionString);
		}

		public void OpenConnection()
		{
			if (_connection.State == ConnectionState.Closed)
			{
				_connection.Open();
			}
		}

		public void CloseConnection()
		{
			if (_connection.State == ConnectionState.Open)
			{
				_connection.Close();
			}
		}

		public void BeginTransaction()
		{
			if (_connection.State == ConnectionState.Closed)
			{
				OpenConnection();
			}

			_transaction = _connection.BeginTransaction();
			_isTransactionActive = true;
		}

		public void CommitTransaction()
		{
			if (_isTransactionActive)
			{
				_transaction.Commit();
				_isTransactionActive = false;
			}
		}

		public void RollbackTransaction()
		{
			if (_isTransactionActive)
			{
				_transaction.Rollback();
				_isTransactionActive = false;
			}
		}

		public DataTable ExecuteQuery(string query, params OdbcParameter[] parameters)
		{
			using (OdbcCommand command = new OdbcCommand(query, _connection, _transaction))
			{
				if (parameters != null)
				{
					command.Parameters.AddRange(parameters);
				}

				using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
				{
					DataTable resultTable = new DataTable();
					adapter.Fill(resultTable);
					return resultTable;
				}
			}
		}

		public int ExecuteNonQuery(string commandText, params OdbcParameter[] parameters)
		{
			using (OdbcCommand command = new OdbcCommand(commandText, _connection, _transaction))
			{
				if (parameters != null)
				{
					command.Parameters.AddRange(parameters);
				}

				return command.ExecuteNonQuery();
			}
		}

		public object ExecuteScalar(string commandText, params OdbcParameter[] parameters)
		{
			using (OdbcCommand command = new OdbcCommand(commandText, _connection, _transaction))
			{
				if (parameters != null)
				{
					command.Parameters.AddRange(parameters);
				}

				return command.ExecuteScalar();
			}
		}

		public void Dispose()
		{
			if (_isTransactionActive)
			{
				RollbackTransaction();
			}

			if (_connection != null)
			{
				CloseConnection();
				_connection.Dispose();
			}
		}
	}
}
